package com.helen.ui.newui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.support.annotation.LayoutRes;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.db.UserHelper;
import com.helen.entity.CheckInEntity;
import com.helen.entity.Checkin;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.utils.JsonUtil;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.ResourcesHelper;
import com.helen.utils.tiputils.MToast;
import com.sch.calendar.CalendarView;
import com.sch.calendar.adapter.VagueAdapter;
import com.sch.calendar.annotation.DayOfMonth;
import com.sch.calendar.annotation.Month;
import com.sch.calendar.entity.Date;
import com.sch.calendar.listener.OnMonthChangedListener;
import com.sch.calendar.util.DateUtil;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2019/1/31
 */
public class CheckInActivity extends BaseActivity {
    @BindView(R.id.calendar_view)
    CalendarView calendarView;
    private final String MONTH_FORMAT = "yyyy-MM";
    private final String DAY_OF_MONTH_FORMAT = "yyyy-MM-dd";
    @BindView(R.id.tv_check_in)
    SuperTextView tvCheckIn;
    private Date today;
    private Map<String, Map<String, Checkin>> checkinMap = new HashMap<>();
    private Map<String, Checkin> monthCheckinMap = new HashMap<>();
    private VagueAdapter<Map<String, Map<String, Checkin>>> vagueAdapter;
    private int year;
    private int month;
    private int dayOfMonth;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_check_in;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        initCalendarView();
        createCheckinData();

    }

    @Override
    protected void updateViews() {

    }

    private void checkInLApi() {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(CheckInActivity.this).getId());
        EasyHttp.post(Constants.API_JSONAPI_SIGN_IN)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MToast.makeTextLong(CheckInActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String s) {
                        mMProgressDialog.dismiss();
                        MyLog.d("yang", "签到==" + s);
                        int code = JsonUtil.getJsonValuesInt(s, "code");
                        String message = JsonUtil.getJsonValuesString(s, "msg");
                        Date today = DateUtil.today();
                        int year = today.getYear();
                        int month = today.getMonth();
                        int dayOfMonth = today.getDayOfMonth();
                        Map<String, Checkin> checkinMap = vagueAdapter.getData().get(DateUtil.formatDate(year, month, dayOfMonth, MONTH_FORMAT));
                        checkinMap.put(DateUtil.formatDate(year, month, dayOfMonth, DAY_OF_MONTH_FORMAT), new Checkin());
                        vagueAdapter.notifyDataSetChanged(year, month);
                        tvCheckIn.setText("已签到");
                        tvCheckIn.setEnabled(false);

                        AlertDialog.Builder builder = new AlertDialog.Builder(CheckInActivity.this);
                        builder.setTitle("温馨提示")
                                .setMessage(message)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {


                                    }
                                });
//                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialogInterface, int i) {
//
//                            }
//                        });
                        builder.create().show();


                    }
                });
    }

    private void checkInListApi(String yearMonth) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("id", UserHelper.getInstance().getloginEntity(CheckInActivity.this).getId());
        params.put("yearMonth", yearMonth);
        EasyHttp.post(Constants.API_JSONAPI_SIGN_IN_LIST)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MToast.makeTextLong(CheckInActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String s) {
                        mMProgressDialog.dismiss();
                        MyLog.d("yang", "签到列表==" + s);
                        String data = PhoneUtils.checkResponseFlag2(CheckInActivity.this, s, TAG);
                        if (data != null) {
                            List<CheckInEntity> list = new Gson().fromJson(data, new TypeToken<List<CheckInEntity>>() {
                            }.getType());


                            for (int i = 0; i < list.size(); i++) {
                                String time = list.get(i).getTime();
                                String[] strTimeArray = time.split("-");
                                MyLog.d("yang", "time==" + time);
                                int year = Integer.valueOf(strTimeArray[0]);
                                int day = Integer.valueOf(strTimeArray[2]);
//                                String month = strTimeArray[1];
                                MyLog.d("yang", "month==" + month);

                                monthCheckinMap.put(DateUtil.formatDate(year, month, day, DAY_OF_MONTH_FORMAT), new Checkin());
                            }

                            calendarView.post(new Runnable() {
                                @Override
                                public void run() {
                                    vagueAdapter.setData(checkinMap);
                                    vagueAdapter.notifyDataSetChanged();
                                }
                            });
                        }

                    }
                });
    }


    // Initialize view for calendar
    private void initCalendarView() {
        calendarView.setCanDrag(false); // can't change month by slide
        calendarView.setScaleEnable(true); // can auto scale calendar when month changed.
        calendarView.setShowOverflowDate(false); // hide overflow date of showing month.
        // Set a listener，callback when month changed.
        calendarView.setOnMonthChangedListener(new OnMonthChangedListener() {
            @Override
            public void onMonthChanged(Date date) {
            }
        });
        // create adapter
        vagueAdapter = new MyVagueAdapter(R.layout.layout_checkin_calendar_item);
        vagueAdapter.setData(new HashMap<String, Map<String, Checkin>>());
        calendarView.setVagueAdapter(vagueAdapter);
    }

    // Generate some data.
    private Map<String, Map<String, Checkin>> createCheckinData() {
        today = DateUtil.today();
        year = today.getYear();
        month = today.getMonth();
        dayOfMonth = today.getDayOfMonth();
        checkinMap.put(DateUtil.formatDate(year, month, dayOfMonth, MONTH_FORMAT), monthCheckinMap);
        checkInListApi(year + "-" + (month + 1));
        return checkinMap;
    }


    @OnClick(R.id.tv_check_in)
    public void onViewClicked() {
        checkInLApi();


    }

    private class MyVagueAdapter extends VagueAdapter<Map<String, Map<String, Checkin>>> {

        MyVagueAdapter(@LayoutRes int dayLayout) {
            super(dayLayout);
        }

        @Override
        public void onBindVague(View itemView, int year, @Month int month, @DayOfMonth int dayOfMonth) {
            ImageView ivCheckinAlready = itemView.findViewById(R.id.iv_checkin_already);
            if (data == null) return;
            // Get the data of current month.
            Map<String, Checkin> monthMap = data.get(DateUtil.formatDate(year, month, dayOfMonth, MONTH_FORMAT));
            // No data of current month.
            if (monthMap == null) {
                ivCheckinAlready.setVisibility(View.GONE);
                return;
            }
            // Get the data of today.
            Checkin history = monthMap.get(DateUtil.formatDate(year, month, dayOfMonth, DAY_OF_MONTH_FORMAT));
            // Show action finished or not.
            ivCheckinAlready.setVisibility(history == null ? View.GONE : View.VISIBLE);
        }

        @Override
        public void flagToday(View todayView) {
            // Highlight today.
            TextView tvDayView = todayView.findViewById(R.id.tv_day_of_month);
            tvDayView.setBackgroundResource(R.mipmap.ic_flag_checkin_calendar_today);
            tvDayView.setTextColor(Color.WHITE);
        }

        @Override
        public void flagNotToday(View dayView, Date date) {
            // Reset the view of not today.
            TextView tvDayView = dayView.findViewById(R.id.tv_day_of_month);
            tvDayView.setBackgroundColor(Color.TRANSPARENT);
            tvDayView.setTextColor(ResourcesHelper.getColor(getApplicationContext(), R.color.appThemeSubTitleColor));
        }
    }
}
